package com.system.service;

import com.system.domain.APPIDConfig;
import com.system.domain.R;
import com.system.domain.SysAppsVersionVo;
import org.apache.maven.artifact.versioning.ComparableVersion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;

@Component
@EnableScheduling
public class HourlyRequestSenderSpring {

    @Resource
    private  APPIDConfig appIdConfig;
//    private static final String TARGET_URL = APPIDConfig.getInstance().getUrl()+"/system/appsVersion/get_version_info/"+ APPIDConfig.getInstance().getAppId();

    @Autowired
    private PrinterService iprinterService;

//    @Scheduled(fixedRate = 60000)
    @Scheduled(fixedRate = 3600000)// 每 1 小时（3600000 毫秒）执行一次
    public void sendHourlyRequest() {
        try {
            sendRequest();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void sendRequest() throws IOException, InterruptedException {

        RestTemplate restTemplate = new RestTemplate();

        // 发送 GET 请求
        // 使用 ParameterizedTypeReference 保留泛型类型信息
        ParameterizedTypeReference<R<SysAppsVersionVo>> typeReference = new ParameterizedTypeReference<R<SysAppsVersionVo>>() {};

        ResponseEntity<R<SysAppsVersionVo>> response = restTemplate.exchange(appIdConfig.getUrl()+"/system/appsVersion/get_version_info/"+ appIdConfig.getAppId(), HttpMethod.GET, null, typeReference);
        R<SysAppsVersionVo> body1 = response.getBody();
        SysAppsVersionVo body = null;
        if (body1 != null) {
            body = body1.getData();
        }
        if (body==null||
                body.getInstallPackageUrl()==null|| body.getInstallPackageUrl().isEmpty()){
            return;
        }else{
            String NEWversionNumber = body.getVersionNumber();
            String nowVersion = appIdConfig.getVersion();
            if(new ComparableVersion(nowVersion).compareTo(new ComparableVersion(NEWversionNumber))<0){
                iprinterService.downloadJar(body);
            }

        }

    }
}